import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Tabs,
  Icon,
  Table,
  Button,
  Modal,
  Popconfirm,
  DatePicker,
  Collapse,
  Select,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GeneralFilterComponent from 'components/GeneralFilterComponent';

const { Option } = Select;
const TabPane = Tabs.TabPane;
const Panel = Collapse.Panel;
const RangePicker = DatePicker.RangePicker;

@connect(({ redPacketStatistics, loading }) => ({
  redPacketStatistics,
  loading: loading.models.redPacketStatistics,
}))

export default class RedPacketStatistics extends PureComponent {
  state = {
    pageStatus: 'dataStatistics',
    collapseStatus: false,
    paramList: {
      pageNo: 1,
      pageSize: 10,
      dateRange: [],
      source: '',
      userId: '',
      userName: '',
      deductType: '',
      giveType: 'batch',
      // status: '',
    },
  };

  componentDidMount() {
    const { paramList } = this.state;
    this.getDataStatistics();
    this.getRedPacketDataStatisticsList();
  };

  getDataStatistics = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {
      startTime: '',
      endTime: '',
    }
    if (paramList.dateRange[0]) {
      [postParam.startTime, postParam.endTime] = [paramList.dateRange[0].format('YYYY-MM-DD hh:mm:ss'), paramList.dateRange[1].format('YYYY-MM-DD hh:mm:ss')];
    } else {
      [postParam.startTime, postParam.endTime] = [moment().subtract(7, 'days').format('YYYY-MM-DD hh:mm:ss'), moment().format('YYYY-MM-DD hh:mm:ss')];
    }
    dispatch({
      type: 'redPacketStatistics/fetchGetRedPacket',
      payload: {
        ...postParam
      }
    });
    dispatch({
      type: 'redPacketStatistics/fetchGetTotalRedPacket',
      payload: {
        ...postParam
      }
    });
  };

  getRedPacketDataStatisticsList = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;

    let postParam = {
      current: paramList.pageNo,
      pageSize: paramList.pageSize,
      startTime: '',
      endTime: '',
    }
    if (paramList.dateRange[0]) {
      [postParam.startTime, postParam.endTime] = [paramList.dateRange[0].format('YYYY-MM-DD hh:mm:ss'), paramList.dateRange[1].format('YYYY-MM-DD hh:mm:ss')];
    } else {
      [postParam.startTime, postParam.endTime] = [moment().subtract(7, 'days').format('YYYY-MM-DD hh:mm:ss'), moment().format('YYYY-MM-DD hh:mm:ss')];
    }
    if (paramList.source) {
      postParam.source = paramList.source;
    }
    dispatch({
      type: 'redPacketStatistics/fetchGetDayRedPacket',
      payload: {
        ...postParam
      }
    });
  };

  getGiveOutStatisticsList = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;

    let paramBuf = {
      current: paramList.pageNo,
      pageSize: paramList.pageSize,
      userId: paramList.userId,
      userName: paramList.userName,
      deductType: paramList.deductType,
      giveType: paramList.giveType,
      source: paramList.source == 'all' ? '' : paramList.source,
      // status: paramList.status,
      startDate: '',
      endDate: '',
    }
    if (paramList.dateRange[0]) {
      [paramBuf.startDate, paramBuf.endDate] = [paramList.dateRange[0].format('YYYY-MM-DD h:mm:ss'), paramList.dateRange[1].format('YYYY-MM-DD h:mm:ss')];
    }
    //过滤''参数
    let postParam = {};
    for (let [key, val] of Object.entries(paramBuf)) {
      if (val !== '') {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'redPacketStatistics/fetchGetReadPacketGiveList',
      payload: {
        ...postParam
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.current;
    paramList.pageSize = pagination.pageSize;
    this.getGiveOutStatisticsList();
  };

  handleFormReset = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getGiveOutStatisticsList();
  };

  handleFormSearch = (value) => {
    const { paramList } = this.state;
    Object.assign(paramList, value);
    paramList.pageNo = 1;
    this.getGiveOutStatisticsList();
  };

  handleDataDateChange = (dates, dateStrings) => {
    const { paramList } = this.state;
    paramList.dateRange = dates;
    paramList.pageNo = 1;
    this.getDataStatistics();
    this.getRedPacketDataStatisticsList();
  };

  handleDataTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.current;
    paramList.pageSize = pagination.pageSize;
    this.getRedPacketDataStatisticsList();
  };

  handleTabChange = (val) => {
    const { paramList } = this.state;
    paramList.pageNo = 1;
    paramList.dateRange = [];
    switch(val) {
      case 'dataStatistics':
        this.getRedPacketDataStatisticsList();
        break;
      case 'giveOut':
        this.getGiveOutStatisticsList();
        break;
      default:
        break;
    }
  };

  handleGiveOutTabChange = (val) => {
    const { paramList } = this.state;
    paramList.giveType = val;
    this.getGiveOutStatisticsList();
  };

  handleCollapseChange = (val) => {
    this.setState({
      collapseStatus: val && val[0]
    })
  };

  handleDataSelectChange = (val) => {
    const { paramList } = this.state;
    paramList.source = val == 'all' ? '' : val;
    paramList.pageNo = 1;
    this.getRedPacketDataStatisticsList();
  };

  reSourceType = (src) => {
    let sourceType = [{
      value: '',
      label: '全部',
    }, {
      value: 'up',
      label: 'sdfz',
    // }, {
    //   value: 'xbeauty',
    //   label: '想美',
    // }, {
    //   value: 'xflower',
    //   label: '信花花',
    }];
    let reLabel = 'unknown';
    sourceType.forEach((val, index, arr) => {
      if (src == val.value) {
        reLabel = val.label
      }
    });
    return reLabel
  };

  reDeductType = (type) => {
    let deductType = [{
      value: 'repay',
      label: '仅还款使用',
    }, {
      value: 'buy-vip-card',
      label: '仅购买会员使用',
    }, {
      value: 'new-user-vip',
      label: '仅新用户首次购买会员使用',
    }, {
      value: 'extend',
      label: '仅展期支付使用',
    }];
    let reLabel = 'unknown';
    deductType.forEach((val, index, arr) => {
      if (type == val.value) {
        reLabel = val.label
      }
    });
    return reLabel
  };

  reStatus = (status) => {
    let sourceType = [{
      value: 'sending',
      label: '发送中',
    }, {
      value: 'send-success',
      label: '发送成功',
    }, {
      value: 'send-fail',
      label: '发送失败',
    }, {
      value: 'part-send-fail',
      label: '部分发送失败',
    }];
    let reLabel = 'unknown';
    sourceType.forEach((val, index, arr) => {
      if (status == val.value) {
        reLabel = val.label
      }
    });
    return reLabel
  };

  render() {
    const { redPacketStatistics: { getRedPacketData, getTotalRedPacketData, getDayRedPacketData, getReadPacketGiveListData }, loading } = this.props;
    const { collapseStatus } = this.state;

    const dataTableColumns = [{
        title: '统计时间',
        dataIndex: 'giveTime',
        key: 'giveTime',
        render: val => `${val}`
    }, {
        title: '发放个数',
        dataIndex: 'giveNum',
        key: 'giveNum',
        render: val => `${val}`
    }, {
        title: '未使用个数',
        dataIndex: 'notUserNum',
        key: 'notUserNum',
        render: val => `${val}`
    }, {
        title: '已使用个数',
        dataIndex: 'userNum',
        key: 'userNum',
        render: val => `${val}`
    }, {
        title: '过期个数',
        dataIndex: 'expiredNum',
        key: 'expiredNum',
        render: val => `${val}`
    }];

    const giveOutBatchTableColumns = [{
        title: '序号',
        dataIndex: 'demo',
        key: 'demo',
        render: (text, record, index) => {
          return <span>{index + 1 + ( getReadPacketGiveListData.pagination.current - 1 ) * getReadPacketGiveListData.pagination.size}</span>
        }
    }, {
        title: '产品类型',
        dataIndex: 'source',
        key: 'source',
        render: (text, record, index) => {
          return <span>{this.reSourceType(text)}</span>
        }
    }, {
        title: '用户',
        dataIndex: 'giveUserNum',
        key: 'giveUserNum',
        render: (text, record, index) => {
          return <span>{text == 'all' ? '全体' : text + '个'}</span>
        }
    }, {
        title: '红包名称',
        dataIndex: 'packetName',
        key: 'packetName',
        render: val => `${val}`
    }, {
        title: '红包金额',
        dataIndex: 'packetAmount',
        key: 'packetAmount',
        render: val => `${val}`
    }, {
        title: '抵扣条件',
        dataIndex: 'deductCondition',
        key: 'deductCondition',
        render: val => `${val}`
    }, {
        title: '抵扣类型',
        dataIndex: 'deductType',
        key: 'deductType',
        render: (text, record, index) => {
          return <span>{this.reDeductType(text)}</span>
        }
    }, {
        title: '发放时间',
        dataIndex: 'giveTime',
        key: 'giveTime',
        render: val => `${val}`
    }, {
        title: '到期时间',
        dataIndex: 'expireTime',
        key: 'expireTime',
        render: val => `${val}`
    }, {
        title: '发放原因',
        dataIndex: 'giveReason',
        key: 'giveReason',
        render: val => `${val}`
    }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record, index) => {
          return <span>{this.reStatus(text)}</span>
        }
    }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        render: val => `${val}`
    }];


    const giveOutSingleTableColumns = [{
        title: '序号',
        dataIndex: 'demo',
        key: 'demo',
        render: (text, record, index) => {
          return <span>{index + 1 + ( getReadPacketGiveListData.pagination.current - 1 ) * getReadPacketGiveListData.pagination.size}</span>
        }
    }, {
        title: '产品类型',
        dataIndex: 'source',
        key: 'source',
        render: (text, record, index) => {
          return <span>{this.reSourceType(text)}</span>
        }
    }, {
        title: '姓名',
        dataIndex: 'userName',
        key: 'userName',
        render: val => `${val}`
    }, {
        title: '用户ID',
        dataIndex: 'userId',
        key: 'userId',
        render: val => `${val}`
    }, {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile',
        render: val => `${val}`
    }, {
        title: '红包名称',
        dataIndex: 'packetName',
        key: 'packetName',
        render: val => `${val}`
    }, {
        title: '红包金额',
        dataIndex: 'packetAmount',
        key: 'packetAmount',
        render: val => `${val}`
    }, {
        title: '抵扣条件',
        dataIndex: 'deductCondition',
        key: 'deductCondition',
        render: val => `${val}`
    }, {
        title: '抵扣类型',
        dataIndex: 'deductType',
        key: 'deductType',
        render: (text, record, index) => {
          return <span>{this.reDeductType(text)}</span>
        }
    }, {
        title: '发放时间',
        dataIndex: 'giveTime',
        key: 'giveTime',
        render: val => `${val}`
    }, {
        title: '到期时间',
        dataIndex: 'expireTime',
        key: 'expireTime',
        render: val => `${val}`
    }, {
        title: '发放原因',
        dataIndex: 'giveReason',
        key: 'giveReason',
        render: val => `${val}`
    }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record, index) => {
          return <span>{this.reStatus(text)}</span>
        }
    }];

    const searchColumns = [{
      type: 'input',
      value: 'userName',
      label: '姓名',
      placeholder: '请输入',
    }, {
      type: 'input',
      value: 'userId',
      label: '用户ID',
      placeholder: '请输入',
    }, {
      type: 'rangePicker',
      value: 'dateRange',
      label: '时间范围',
      placeholder: ['起始时间', '结束时间'],
      showQuickChoose: true,
    }, {
      type: 'select',
      value: 'source',
      label: '产品类型',
      placeholder: '请选择',
      selectOption:  [{
        value: 'all',
        label: '全部',
      }, {
        value: 'up',
        label: 'sdfz',
      // }, {
      //   value: 'xbeauty',
      //   label: '想美',
      // }, {
      //   value: 'xflower',
      //   label: '信花花',
      }]
    }, {
      type: 'select',
      value: 'deductType',
      label: '抵扣类型',
      placeholder: '请选择',
      selectOption: [{
        value: 'repay',
        label: '仅还款使用',
      }, {
        value: 'buy-vip-card',
        label: '仅购买会员使用',
      }, {
        value: 'new-user-vip',
        label: '仅新用户首次购买会员使用',
      }, {
        value: 'extend',
        label: '仅展期支付使用',
      }],
      width: 200,
    // }, {
    //   type: 'select',
    //   value: 'status',
    //   label: '红包状态',
    //   placeholder: '请选择',
    //   selectOption: [{
    //     value: '',
    //     label: '全部',
    //   }, {
    //     value: 'valid',
    //     label: '有效',
    //   }, {
    //     value: 'invalid',
    //     label: '失效',
    //   }]
    }]

    const headerList = [{
      label: '已发放个数',
      value: getTotalRedPacketData.giveNum ? getTotalRedPacketData.giveNum : '/',
    }, {
      label: '未使用个数',
      value: getTotalRedPacketData.notUserNum ? getTotalRedPacketData.notUserNum : '/',
    }, {
      label: '已使用个数',
      value: getTotalRedPacketData.userNum ? getTotalRedPacketData.userNum : '/',
    }, {
      label: '过期个数',
      value: getTotalRedPacketData.expiredNum ? getTotalRedPacketData.expiredNum : '/',
    }];
    
    const listHeaderItems = headerList.map((item) =>
      <Col span={5} key={item.label}>
        <div>
          <span>{item.label}</span>
        </div>
        <div>
          <span style={{fontWeight: 500}}>{item.value}</span>
        </div>
      </Col>
    );

    const listItems = getRedPacketData.map((item) =>
      <Row style={{textAlign: 'center', fontSize: 16, lineHeight: "20px", marginBottom: 6, marginTop: 6}} key={item.source}>
        <Col span={2}>
          <div>
            <span>{this.reSourceType(item.source)}</span>
          </div>
        </Col>
        <Col span={5}>
          <div>
            <span>{item.giveNum}</span>
          </div>
        </Col>
        <Col span={5}>
          <div>
            <span>{item.notUserNum}</span>
          </div>
        </Col>
        <Col span={5}>
          <div>
            <span>{item.userNum}</span>
          </div>
        </Col>
        <Col span={5}>
          <div>
            <span>{item.expiredNum}</span>
          </div>
        </Col>
      </Row>
    );

    return (
      <PageHeaderLayout>
        <Card bordered={false}>

          <Tabs defaultActiveKey="dataStatistics" onChange={this.handleTabChange}>

            <TabPane tab="数据统计" key="dataStatistics">
              <div style={{marginBottom: 20}}>
                <RangePicker
                  ranges={{
                    近7天: [moment().subtract(7, 'days'), moment()],
                    近14天: [moment().subtract(14, 'days'), moment()],
                    近30天: [moment().subtract(30, 'days'), moment()],
                  }}
                  onChange={this.handleDataDateChange}
                  defaultValue={[moment().subtract(7, 'days'), moment()]}
                  allowClear={false}
                />
              </div>
              <div style={{marginBottom: 20}}>
                <Collapse onChange={this.handleCollapseChange}>
                  <Panel showArrow={false} header={
                    <Row style={{textAlign: 'center', fontSize: 16, lineHeight: "40px", marginLeft: 4, marginRight: 16}}>
                      <Col span={2}></Col>
                      {listHeaderItems}
                      <Col span={2}>
                        <div style={{lineHeight: "80px"}}>
                        {
                          collapseStatus ? <Icon type="up" theme="outlined" /> : <Icon type="down" theme="outlined" />
                        }
                        </div>
                      </Col>
                    </Row>
                  }>
                    {listItems}
                  </Panel>
                </Collapse>
              </div>
              <div style={{marginBottom: 20}}>
                <Select placeholder="全部" style={{width: 120}} onChange={this.handleDataSelectChange}>
                  <Option value="all">全部</Option>
                  <Option value="up">sdfz</Option>
                  {/* <Option value="xbeauty">想美</Option>
                  <Option value="xflower">信花花</Option> */}
                </Select>
              </div>
              <GeneralTableComponent
                loading={loading}
                data={getDayRedPacketData}
                columns={dataTableColumns}
                onChange={this.handleDataTableChange}
                showSizeChanger
              />
            </TabPane>

            <TabPane tab="发放统计" key="giveOut">
              <div style={{marginBottom: 20}}>
                <GeneralFilterComponent
                itemList={searchColumns}
                onClear={this.handleFormReset}
                onSearch={this.handleFormSearch}
                ></GeneralFilterComponent>
              </div>
              <Tabs defaultActiveKey="batch" onChange={this.handleGiveOutTabChange}>
                <TabPane tab="批量发放" key="batch">
                  <GeneralTableComponent
                    loading={loading}
                    data={getReadPacketGiveListData}
                    columns={giveOutBatchTableColumns}
                    onChange={this.handleStandardTableChange}
                    showSizeChanger
                  />
                </TabPane>
                <TabPane tab="单独发放" key="single">
                  <GeneralTableComponent
                    loading={loading}
                    data={getReadPacketGiveListData}
                    columns={giveOutSingleTableColumns}
                    onChange={this.handleStandardTableChange}
                    showSizeChanger
                  />
                </TabPane>
              </Tabs>
            </TabPane>

          </Tabs>

        </Card>
      </PageHeaderLayout>
    );
  }
}
